package at.sysarch.filter;

import java.awt.image.renderable.ParameterBlock;
import javax.media.jai.JAI;
import javax.media.jai.KernelJAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.RenderedOp;
import at.sysarch.utils.ImageChangedEvent;
import at.sysarch.utils.ImageChangedListener;
import at.sysarch.utils.KernelHelper;

public class OpeningFilter extends AbstractListenerManager implements ImageChangedListener {

	private PlanarImage _image = null;
	private KernelJAI _erodeKernel = KernelHelper.getKernel(11, 11);
	private KernelJAI _dilateKernel = KernelHelper.getKernel(11, 11);
	private int _erodeKernelSize = 11;
	private int _dilateKernelSize = 11;
	
	public void setInputImage(PlanarImage image) {
		_image = image;
		updateImage();
	}

	@Override
	public void imageChanged(ImageChangedEvent event) {
		setInputImage(event.getImage());
	}

	private void updateImage() {
		RenderedOp image = open();
		fireImageChanged(image);
	}

	private RenderedOp open() {
		ParameterBlock erodeParams = new ParameterBlock();
		erodeParams.addSource(_image);
		erodeParams.add(_erodeKernel);
		PlanarImage erodedImage = JAI.create("erode", erodeParams);
		
		ParameterBlock dilateParams = new ParameterBlock();
		dilateParams.addSource(erodedImage);
		dilateParams.add(_dilateKernel);
		
		return JAI.create("dilate", dilateParams);
	}

	public int getErodeKernelSize() {
		return _erodeKernelSize;
	}

	public void setErodeKernelSize(int erodeKernelSize) {
		_erodeKernelSize = erodeKernelSize;
		_erodeKernel = KernelHelper.getKernel(erodeKernelSize, erodeKernelSize);
		updateImage();
	}

	public int getDilateKernelSize() {
		return _dilateKernelSize;
	}

	public void setDilateKernelSize(int dilateKernelSize) {
		_dilateKernelSize = dilateKernelSize;
		_dilateKernel = KernelHelper.getKernel(dilateKernelSize, dilateKernelSize);
		updateImage();
	}
}
